package com.neulogistics.contrib.transfercenter.api.application.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.neulogistics.contrib.transfercenter.api.service.ThreadLocalService;
import com.neulogistics.infrastructure.common.token.JwtTokenUtil;
import com.neulogistics.infrastructure.common.token.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        // 在请求之前进行处理
//        String accessToken = request.getHeader(JwtTokenUtil.ACCESS_HEADER);
//        if(StrUtil.isBlank(accessToken)){
//            response.setStatus(401);
//            return false;
//        }
//
//        // 获取用户信息
//        JSONObject userJson = JwtTokenUtil.parse(accessToken);
//        LoginUser loginUser = new LoginUser();
//        BeanUtil.copyProperties(userJson, loginUser);
//
//        // 存入ThreadLocal
//        ThreadLocalService.loginUser.set(loginUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // 请求处理完成后的处理，可以在这个方法中对响应进行进一步处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) throws Exception {
        // 释放信息
        ThreadLocalService.loginUser.remove();
    }
}